#include <iostream>
#include <string>
#include <set>
#include <fstream>
#include "LOG.hpp"
#include <cstdio>

using namespace std;

const string sep = " ";

class Commend
{
private:
    void Load(string& conf)
    {
        // 1.打开文件
        ifstream in(conf);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s error", conf.c_str());
            return;
        }
        // 2.读取
        string line;
        while (getline(in, line)) // 从in 读取内容到line当中
        {
            LOG(DEBUG, "load command [%s] success", line.c_str());
            _safe_cmd.insert(line);
        }
        in.close();
    }
    string PrefixCommand(const string &cmd)
    {
        if(cmd.empty()) return string();
        auto pos = cmd.find(sep);
        if(pos == string::npos) return cmd;
        else return cmd.substr(0, pos);
    }
    bool Safecmd(const string &cmd)
    {
        string prefix = PrefixCommand(cmd); // ls -a -l , touch a.txt
        auto iter = _safe_cmd.find(prefix);
        if (iter == _safe_cmd.end())
        {
            return false;
        }
        return true;
    }

public:
    Commend(const string &conf_path)
        : _conf_path(conf_path)
    {
        Load(_conf_path);
    }

    string Excute(const string &cmd)
    {
        string result;
        if (Safecmd(cmd))
        {
            FILE *c = popen(cmd.c_str(), "r");
            if (c == nullptr)
                return "fail";
            char buffer[1024];
            while (fgets(buffer, sizeof(buffer), c) != NULL)
            {
                result += buffer;
            }

            pclose(c);
        }
        else 
            return "坏人";
        return result;
    }
    ~Commend()
    {
    }

private:
    set<string> _safe_cmd;
    string _conf_path;
};